<template>
  <div class="manOrderHome">
    <pull-to-refresh @load="load">
      <group :gutter="0">
        <cell :title="'待处理'"
              is-link
              :border-intent="false"
              :style="'font-size: 15px'"
              :arrow-direction="showContent001 ? 'up' : 'down'"
              @click.native="showCreatOrder">
          <img slot="icon" style="width: 0.2rem; margin-right: 0.05rem" src="~assets/images4/icon-daichuli@2x.png"/>
          <span slot="title">待处理<span  style="margin-left: 0.05rem; color: #999">({{content001Num}})</span></span>
        </cell>
        <template>
          <ul class="toCreatList" v-show="showContent001">
            <li v-for="item in toCreatedList" @click="toCreatOrder(item)">
              <div class="left pl15">
                <div>
                  <span>{{_dateFormat(item.createdTime)}}</span>
                  <!--<span class="c666 ml15">{{item.createdTime.substring(0,10)}}</span>-->
                  <span class="c666   ml15 mr15">类型</span>
                  <span v-if="item.workOrderType">{{item.workOrderType.name}}</span>
                </div>
                <div class="mt5" v-if="item.workOrderType && item.workOrderType.serviceType == 'OUT'">
                  <span class="c666  mr15">客户联系人</span>
                  <span>{{item.linkMan}}</span>
                </div>
                <div class="mt5" v-if="item.workOrderType && item.workOrderType.serviceType == 'IN' && item.engineer">
                  <span class="c666  mr15">任务执行人</span>
                  <span>{{item.engineer.nickName}}</span>
                </div>
              </div>
              <div class="right blue">去处理</div>
            </li>
          </ul>
        </template>
        <cell is-link
              :border-intent="false"
              :style="'font-size: 15px'"
              :arrow-direction="showContent002 ? 'up' : 'down'"
              @click.native="showDistributeOrder">
          <img slot="icon" style="width: 0.2rem; margin-right: 0.05rem" src="~assets/images4/icon-daipaifa@2x.png"/>
          <span slot="title">待派发<span  style="margin-left: 0.05rem; color: #999">({{content002Num}})</span></span>
        </cell>
        <template>
          <ul class="toCreatList" v-show="showContent002">
            <li v-for="item in toDistributeList" @click="toDistribute(item)">
              <div class="left pl15">
                <div>
                  <span>{{item.code}}</span>
                  <span class="c666 ml15">{{_dateFormat(item.createdTime)}}</span>
                </div>
                <div class="mt5">
                  <span class="c666  mr15">客户联系人</span>
                  <span>{{item.linkMan}}</span>
                </div>
              </div>
              <div class="right blue">去派发</div>
            </li>
          </ul>
        </template>
        <cell :title="'已派发'"
              is-link
              :border-intent="false"
              :style="'font-size: 15px'"
              :arrow-direction="showContent003 ? 'up' : 'down'"
              @click.native="showDistributedOrder">
          <img slot="icon" style="width: 0.2rem; margin-right: 0.05rem" src="~assets/images4/icon-yipaifa@2x.png"/>
          <span slot="title">已派发<span  style="margin-left: 0.05rem; color: #999">({{content003Num}})</span></span>
        </cell>
        <template>
          <ul class="toCreatList" v-show="showContent003">
            <li v-for="(item, index) in reDistributeList" @click="checkInOrder(item.id,item.workOrderType.serviceType)">
              <div class="left pl15">
                <div>
                  <span>{{item.code}}</span>
                  <span class="c666 ml15">{{_dateFormat(item.createdTime)}}</span>
                </div>
                <div class="mt5">
                  <span class="c666  mr15">工程师</span>
                  <span>{{item.engineer.nickName}}</span>
                </div>
              </div>
              <div class="right blue" v-if="item.workOrderType.serviceType == 'OUT' && item.systemStatus == 1" @click.stop="distributeAndCancle(item.id, index)">异常处理</div>
              <div class="right blue" v-if="item.workOrderType.serviceType == 'OUT' && item.systemStatus == 2" @click.stop="onlyCancle(item.id, index)">异常处理</div>
              <div class="right blue" v-if="item.workOrderType.serviceType == 'OUT' && item.systemStatus !== 1 && item.systemStatus !== 2" @click.stop="deferAndStop(item.id, index)">异常处理</div>
              <div class="right blue" v-if="item.workOrderType.serviceType == 'IN'" @click.stop="checkInOrder(item.id,item.workOrderType.serviceType)">查看</div>
            </li>
          </ul>
        </template>
        <cell :title="'待质检'"
              is-link
              :border-intent="false"
              :style="'font-size: 15px'"
              :arrow-direction="showContent004 ? 'up' : 'down'"
              @click.native="showQualityOrder">
          <img slot="icon" style="width: 0.2rem; margin-right: 0.05rem" src="~assets/images4/icon-zhijian@2x.png"/>
          <span slot="title">待质检<span  style="margin-left: 0.05rem; color: #999">({{toQualityList.length}})</span></span>
        </cell>
        <template>
          <ul class="toCreatList" v-show="showContent004">
            <li v-for="item in toQualityList" @click="toQuality(item.id)">
              <div class="left pl15">
                <div>
                  <span>{{item.code}}</span>
                  <span class="c666 ml15">{{_dateFormat(item.createdTime)}}</span>
                </div>
                <div class="mt5">
                  <span class="c666  mr15">工程师</span>
                  <span>{{item.engineer.nickName}}</span>
                </div>
              </div>
              <div class="right blue">去质检</div>
            </li>
          </ul>
        </template>
        <cell :title="'已完成'"
              is-link
              :border-intent="false"
              :style="'font-size: 15px'"
              :arrow-direction="showContent005 ? 'up' : 'down'"
              @click.native="showFinishOrder">
          <img slot="icon" style="width: 0.2rem; margin-right: 0.05rem" src="~assets/images4/icon-tongyi@2x.png"/>
          <span slot="title">已完成<span  style="margin-left: 0.05rem; color: #999">({{content005Num}})</span></span>
        </cell>
        <template>
          <ul class="toFinishList" v-show="showContent005">
            <li v-for="item in finishedList">
              <div class="finishList" v-if="item.workOrderType.serviceType == 'IN' && item.systemStatus == 7 && !item.evaluate" @click="goEvaluate(item)">
                <div class="left pl15">
                  <div>
                    <span>{{item.code}}</span>
                    <span class="c666 ml15">{{_dateFormat(item.createdTime)}}</span>
                  </div>
                  <div class="mt5">
                    <span class="c666  mr15">工程师</span>
                    <span>{{item.engineer.nickName}}</span>
                  </div>
                </div>
                <div class="right blue">去评价</div>
              </div>
              <div class="finishList" v-else @click="goFinishOrder(item)">
                <div class="left pl15">
                  <div>
                    <span>{{item.code}}</span>
                    <span class="c666 ml15">{{_dateFormat(item.createdTime)}}</span>
                  </div>
                  <div class="mt5">
                    <span class="c666  mr15">工程师</span>
                    <span>{{item.engineer.nickName}}</span>
                  </div>
                </div>
                <div class="right blue">关闭工单</div>
              </div>
            </li>
          </ul>
        </template>
      </group>
    </pull-to-refresh>
    <div class="addOrder" @click="addOrder()"></div>

    <div v-transfer-dom>
      <popup v-model="addPopup" style="background-color: #fff">
        <popup-header
          left-text="取消"
          right-text="确认"
          title="选择新建工单类型"
          :show-bottom-border="false"
          @on-click-left="showPopup"
          @on-click-right="showPopup"></popup-header>
        <group gutter="0">
          <radio :options="['内部工单']" @click.native="goAddOrder('IN')"></radio>
          <radio :options="['外部工单']" @click.native="goAddOrder('OUT')"></radio>
        </group>
      </popup>
    </div>

    <actionsheet
      v-model="show1"
      :menus="menu1"
      theme="android"
      @on-click-menu="clickMenu">
    </actionsheet>
    <actionsheet
      v-model="show2"
      :menus="menu2"
      theme="android"
      @on-click-menu="clickMenu">
    </actionsheet>
    <actionsheet
      v-model="show3"
      :menus="menu3"
      theme="android"
      @on-click-menu="clickMenu">
    </actionsheet>

    <div v-transfer-dom>
      <confirm
        v-model="deferConfirm"
        :show-cancel-button="false"
        :title="'工单延期'"
        @on-confirm="ondeferConfirm">
        <datetime-range title="截止时间" placeholder="请选择截止时间" :start-date="_dateFormat(new Date())"
                        :end-date="_dateFormat(new Date(new Date()-(-1000*60*60*24*15)))"
                        v-model="preFinishedTime"></datetime-range>
        <datetime-range title="预约时间" placeholder="请选择预约时间" :start-date="_dateFormat(new Date())"
                        :end-date="_dateFormat(new Date(new Date()-(-1000*60*60*24*15)))"
                        v-model="appointTime"></datetime-range>
      </confirm>
    </div>
  </div>
</template>

<script>
  import {Tab, TabItem, Swiper, SwiperItem,Group,Cell ,CellBox, CellFormPreview,PopupHeader, Popup, TransferDom, Radio,Actionsheet,Confirm,DatetimeRange } from 'vux'
  import PullToRefresh from "../common/PullToRefresh";
  export default {
    name: "ManOrderHome",
    components: {PullToRefresh, Tab, TabItem, Swiper, SwiperItem,Group,Cell ,CellBox, CellFormPreview,PopupHeader, Popup, TransferDom, Radio,Actionsheet,Confirm,DatetimeRange },
    directives: {
      TransferDom
    },
    data() {
      return {
        list: [
          '外部工单',
          '内部工单',
        ],
        currentIndex: 0,
        showContent001: false,
        showContent002: false,
        showContent003: false,
        showContent004: false,
        showContent005: false,
        content001Num: 0,
        content002Num: 0,
        content003Num: 0,
        content004Num: 0,
        content005Num: 0,
        toCreatedList: [],
        toDistributeList: [],
        reDistributeList: [],
        toQualityList: [],
        finishedList: [],
        addPopup: false,
        show1: false,
        show2: false,
        show3: false,
        menu1: {
          distribute: '重新派发',
          cancel: '工单取消',
        },
        menu2: {
          defer: '工单延期',
          stop: '工单终止',
        },
        menu3: {
          cancel: '工单取消',
        },
        currentOrderId: '',
        index: Number, //当前操作已派发工单列表的下标
        deferConfirm: false,
        appointTime: [],
        preFinishedTime: [],
      }
    },
    mounted() {
      this.$getUserInfo().then(user=> {
        this.userInfo = user
        let data = {
          search: {
            fields: this.userInfo.id
          }
        }
        this.$http.get('/work/api/workorder/count/backgrounder').then(res=> {
          let data = res.data.data
          this.content001Num = data.preCreateCount   // 待创建
          this.content002Num = data.distributeCount  // 待派发
          this.content003Num = data.receiveCount     // 已派发
          this.content004Num = data.qualityCount     // 待质检
          this.content005Num = data.finishedCount    // 已完成
        })
        this.websocket()
    //     this.getCreatOrder()
    //     this.getDistributedOrder()
     //    this.getDistributeOrder()
     //    this.getFinishOrder()
        this.getQualityOrder()

      })
    },
    methods: {
      showPopup: function () {
        this.addPopup = !this.addPopup
      },
      showCreatOrder: function() {
        this.showContent001 = !this.showContent001
        if (this.showContent001)
        this.getCreatOrder()
      },
      showDistributeOrder: function() {
        this.showContent002 = !this.showContent002
        if (this.showContent002)
          this.getDistributeOrder()
      },
      showDistributedOrder: function() {
        this.showContent003 = !this.showContent003
        if (this.showContent003)
          this.getDistributedOrder()
      },
      showQualityOrder: function() {
        this.showContent004 = !this.showContent004
        if (this.showContent004)
          this.getQualityOrder()
      },
      showFinishOrder: function() {
        this.showContent005 = !this.showContent005
        if (this.showContent005)
          this.getFinishOrder()
      },
      getCreatOrder: function () {
        // 待创建的用户请求
        this.$http.get('/work/api/request?backgrounderId='+this.userInfo.id+'&status=0&noPage=true').then(res=>{
          this.toCreatedList = res.data.data
        })
      },
      getDistributeOrder: function () {
        // 待派发的工单
        this.$http.get('/work/api/workorder?backgrounderId='+this.userInfo.id+'&systemStatus=0&noPage=true').then(res=>{
          this.toDistributeList = res.data.data
        })
      },
      getDistributedOrder: function () {
        // 已派发的工单
        this.$http.get('/work/api/workorder?backgrounderId='+this.userInfo.id+'&systemStatus=1&systemStatus=2&&systemStatus=3&&systemStatus=4&&systemStatus=5&noPage=true').then(res=>{
          this.reDistributeList = res.data.data
        })
      },
      getQualityOrder: function () {
        // 待质检的工单
        this.$http.get('/work/api/workorder?backgrounderId='+this.userInfo.id+'&systemStatus=6&noPage=true').then(res=>{
          this.toQualityList = res.data.data
        })
      },
      getFinishOrder: function () {
        // 完成的工单
        this.$http.get('/work/api/workorder?backgrounderId='+this.userInfo.id+'&systemStatus=7&&systemStatus=8&&systemStatus=9&noPage=true').then(res=>{
          this.finishedList = res.data.data
        })
      },

      toCreatOrder: function (item) {
        this.$router.push({path: '/management/manRequestHandle',query: {requestId: item.id}})
      },
      toDistribute: function (item) {
        if (item.workOrderType.serviceType == 'OUT' && (item.systemStatus == 1 || item.systemStatus == 0))
        this.$router.push({path: '/management/manDistributeOrder',query: {orderId: item.id}})
      },
      toQuality: function (id){
        this.$router.push({path: '/management/manQualityServiceItem',query: {orderId: id}})
      },
      goEvaluate: function(item){
        this.$router.push({path: '/management/manEvaluateInOrder',query: {orderId: item.id}})
      },
      goFinishOrder: function (item) {
        if (item.workOrderType.serviceType == 'IN') {
          this.$router.push({path: '/management/manCloseInOrder',query: {orderId: item.id}
          })
        } else {
          this.$router.push({
            path: '/management/manCloseOrder', query: {orderId: item.id}
          })
        }
      },
      clickMenu: function (key) {
        let that = this
        if (key == 'distribute') {
          this.$router.push({path: '/management/manDistributeOrder',query: {orderId: this.currentOrderId}})
        } else if (key == 'cancel') {
          this.$vux.confirm.show({
            title: '提醒',
            content: '你确定要取消吗',
            onShow () {
            },
            onHide () {
            },
            onCancel () {
            },
            onConfirm () {
              that.$http.put('/work/api/workorder/cancel/'+that.currentOrderId).then(res=>{
                that.$vux.toast.show({
                  content: '取消成功'
                })
                that.reDistributeList.remove(that.reDistributeList[that.index])
              })
            }
          })
        } else if (key == 'defer') {
          this.deferConfirm = !this.deferConfirm
        } else if (key == 'stop') {
          this.$vux.confirm.show({
            title: '提醒',
            content: '你确定要终止吗',
            onShow () {
            },
            onHide () {
            },
            onCancel () {
            },
            onConfirm () {
              that.$http.put('/work/api/workorder/termination/'+that.currentOrderId).then(res=>{
                that.$vux.toast.show({
                  content: '终止成功'
                })
                that.reDistributeList.remove(that.reDistributeList[that.index])
              })
            }
          })
        }
      },
      distributeAndCancle: function (id, index) {
        this.show1 = !this.show1
        this.currentOrderId = id
        this.index = index
      },
      onlyCancle: function (id, index) {
        this.show3 = !this.show3
        this.currentOrderId = id
        this.index = index
      },
      deferAndStop: function (id, index) {
        this.show2 = !this.show2
        this.currentOrderId = id
        this.index = index
      },
      checkInOrder: function (id,type) {
        if (type =='IN') {
          this.$router.push({path: '/management/manOrderInInfo', query: {orderId: id}})
        } else if (type == "OUT") {
          this.$router.push({path: '/management/manOrderOutInfo', query: {orderId: id}})
        }
      },
      ondeferConfirm: function (){  // 工单延期
        if (this.appointTime.length == 0 ||  this.preFinishedTime.length == 0){
          this.$vux.alert.show({
            title: '提示',
            content: '请填写时间'
          })
        }
        let data = {
          appointTime: this.arrayToDate(this.appointTime, 'yyyy-mm-dd HH:MM:SS'),
          preFinishedTime: this.arrayToDate(this.preFinishedTime, 'yyyy-mm-dd HH:MM:SS'),
        }
        console.log(this.appointTime)

        this.$http.put('/work/api/workorder/postpone/'+this.currentOrderId,data, {headers:{"Content-Type": "application/json"}}).then(res=>{
          this.$vux.toast.show({
            text: '延期成功'
          })
        })
      },
      // 时间转换
      arrayToDate(arr) {
        if(arr.length == 0 ){
          return null
        }
        return this._dateFormat(arr[0]+' '+arr[1]+':'+arr[2]+':00', 'YYYY-MM-DD hh:mm:ss')
      },
      addOrder: function () {
        this.showPopup()
      },
      goAddOrder: function (para) {
        if (para === 'OUT') {
          this.$router.push({path: '/management/manCreatedOrder', query: {newOrder: true}})
        } else if (para === 'IN'){
          this.$router.push({path: '/management/manCreatedInOrder', query: {newOrder: true}})
        }
      },
      load(resolve) {
        this.$router.go(0)
        setTimeout(() => {
          resolve();
        }, 500)
      },
      websocket () {
        let host = ''
        if (window.location.host.indexOf('gongdan.xwseries') > -1){
          host = '119.23.224.29:9003'
        } else if (window.location.host.indexOf('test.xwseries') > -1 || window.location.host.indexOf('localhost') > -1) {
          host = '192.168.1.218:9003'
        }
        let ws = new WebSocket('ws://'+ host +'/work/webSocketCore/'+this.$store.state.user.userInfo.id)
        ws.onopen = () => {
          // Web Socket 已连接上，使用 send() 方法发送数据
          console.log('连接成功')
        }
        ws.onmessage = evt => {
          console.log('数据已接收...')

          let reData = JSON.parse(evt.data)
          console.log(reData)
          if (reData.type == 0) {
            this.getQualityOrder()
          }

        }
        ws.onclose = function () {
          // 关闭 websocket
          console.log('连接已关闭...')
        }
        // 路由跳转时结束websocket链接
        this.$router.afterEach(function () {
          ws.close()
        })
      },
    }
  }
</script>

<style lang="less">
  .vux-popup-dialog{
    z-index: 6000 !important;
  }
  .weui-actionsheet__cell{
    text-align: center !important;
  }
  .manOrderHome {
    .toCreatList {
      font-size: 0.13rem;
      li{
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: solid 1px #ebebeb;
        padding: 0.05rem 0.15rem 0.05rem 0 ;
        .right {
          width: 0.7rem;
          height: 0.4rem;
          line-height: 0.4rem;
          text-align: right;
        }
      }
    }
    .toFinishList{
      .finishList{
        font-size: 0.13rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: solid 1px #ebebeb;
        padding: 0.05rem 0.15rem 0.05rem 0 ;
      }
    }
    .addOrder{
      width: 0.5rem;
      height: 0.5rem;
      position: fixed;
      z-index: 2;
      bottom: 0.3rem;
      left: 50%;
      background: url("~assets/images4/icon-tianjiabaoxiao@2x.png") no-repeat;
      background-size: 100%;
      transform: translateX(-50%);
    }

  }
</style>
